import sys
import os
from fastapi import APIRouter, HTTPException, Query
from typing import List

# 添加项目根目录到Python路径
backend_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, backend_path)

# 修复导入路径
from api import fault_api
from schemas.fault_schema import FaultDetail, FaultDetailCreate, FaultCount, FaultCountCreate, ManufacturerStat, ManufacturerStatCreate, FaultDescription

router = APIRouter()

@router.get("/details")
def get_fault_details(
    page: int = Query(1, ge=1, description="页码，从1开始"),
    page_size: int = Query(7, ge=1, le=100, description="每页记录数")
):
    """获取故障明细（支持分页）"""
    try:
        return fault_api.get_fault_details(page, page_size)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/counts")
def get_fault_counts(
    page: int = Query(1, ge=1, description="页码，从1开始"),
    page_size: int = Query(10, ge=1, le=100, description="每页记录数")
):
    """获取故障数量统计（支持分页）"""
    try:
        return fault_api.get_fault_counts(page, page_size)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/manufacturers")
def get_manufacturer_stats(
    page: int = Query(1, ge=1, description="页码，从1开始"),
    page_size: int = Query(5, ge=1, le=100, description="每页记录数")
):
    """获取厂家故障统计（支持分页）"""
    try:
        return fault_api.get_manufacturer_stats(page, page_size)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/description", response_model=FaultDescription)
def get_fault_description():
    """获取详细故障描述"""
    try:
        return fault_api.get_fault_description()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/process")
def process_fault_data():
    """处理故障数据"""
    try:
        result = fault_api.process_fault_data()
        return {"message": "Fault data processed successfully", "result": result}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))